const Service = require('egg').Service;

class LostAndFoundService extends Service {
    // 创建失物招领物品
    async create(itemData) {
        const { ctx } = this;

        // 创建物品
        const item = await ctx.model.LostAndFound.create({
            ...itemData,
            created_at: new Date(),
            updated_at: new Date(),
        });

        // 关联用户信息
        const itemWithUser = await ctx.model.LostAndFound.findByPk(item.item_id, {
            include: [{
                model: ctx.model.User,
                as: 'publisher',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }]
        });

        return itemWithUser;
    }

    // 获取失物招领列表（分页 + 模糊查询）
    async getItems(query) {
        const { ctx } = this;
        const { Op } = this.app.Sequelize;
        const { page = 1, pageSize = 10, category, status, title } = query;

        // 构建查询条件
        const where = {};

        // 分类筛选
        if (category) {
            where.category = category;
        }

        // 状态筛选
        if (status !== undefined && status !== '') {
            where.status = parseInt(status);
        }

        // 模糊查询 - 修复：只使用 title 参数搜索标题和描述
        if (title) {
            where[Op.or] = [
                {
                    title: {
                        [Op.like]: `%${title}%`
                    }
                },
                {
                    description: {
                        [Op.like]: `%${title}%`
                    }
                }
            ];
        }

        const options = {
            where,
            include: [{
                model: ctx.model.User,
                as: 'publisher',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.LostAndFound.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 获取简单列表（不关联用户信息 + 分页 + 模糊查询）
    async getItemsSimple(query) {
        const { ctx } = this;
        const { Op } = this.app.Sequelize;
        const { page = 1, pageSize = 10, category, status, title } = query;

        // 构建查询条件
        const where = {};

        // 分类筛选
        if (category) {
            where.category = category;
        }

        // 状态筛选
        if (status !== undefined && status !== '') {
            where.status = parseInt(status);
        }

        // 模糊查询 - 修复：只使用 title 参数搜索标题和描述
        if (title) {
            where[Op.or] = [
                {
                    title: {
                        [Op.like]: `%${title}%`
                    }
                },
                {
                    description: {
                        [Op.like]: `%${title}%`
                    }
                }
            ];
        }

        const options = {
            where,
            attributes: ['item_id', 'title', 'description', 'category', 'status', 'created_at'],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.LostAndFound.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 根据ID获取物品详情
    async getItemById(itemId) {
        const { ctx } = this;

        const item = await ctx.model.LostAndFound.findByPk(itemId, {
            include: [{
                model: ctx.model.User,
                as: 'publisher',
                attributes: ['user_id', 'nickname', 'avatar', 'phone', 'email']
            }]
        });

        if (!item) {
            throw new Error('物品不存在');
        }

        return item;
    }

    // 获取用户发布的物品（分页 + 模糊查询）
    async getUserItems(userId, query) {
        const { ctx } = this;
        const { Op } = this.app.Sequelize;
        const { page = 1, pageSize = 10, category, status, title } = query;

        // 构建查询条件
        const where = { user_id: userId };

        // 分类筛选
        if (category) {
            where.category = category;
        }

        // 状态筛选
        if (status !== undefined && status !== '') {
            where.status = parseInt(status);
        }

        // 模糊查询 - 修复：只使用 title 参数搜索标题和描述
        if (title) {
            where[Op.or] = [
                {
                    title: {
                        [Op.like]: `%${title}%`
                    }
                },
                {
                    description: {
                        [Op.like]: `%${title}%`
                    }
                }
            ];
        }

        const options = {
            where,
            include: [{
                model: ctx.model.User,
                as: 'publisher',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }],
            limit: parseInt(pageSize),
            offset: (parseInt(page) - 1) * parseInt(pageSize),
            order: [['created_at', 'DESC']]
        };

        const { count, rows } = await ctx.model.LostAndFound.findAndCountAll(options);

        return {
            list: rows,
            pagination: {
                page: parseInt(page),
                pageSize: parseInt(pageSize),
                total: count,
                totalPages: Math.ceil(count / pageSize)
            }
        };
    }

    // 更新物品信息
    async updateItem(itemId, updateData) {
        const { ctx } = this;

        // 检查物品是否存在
        const item = await ctx.model.LostAndFound.findByPk(itemId);
        if (!item) {
            throw new Error('物品不存在');
        }

        // 更新物品信息
        await item.update({
            ...updateData,
            updated_at: new Date()
        });

        // 返回更新后的物品信息（关联用户）
        const updatedItem = await ctx.model.LostAndFound.findByPk(itemId, {
            include: [{
                model: ctx.model.User,
                as: 'publisher',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }]
        });

        return updatedItem;
    }

    // 更新物品状态
    async updateItemStatus(itemId, status) {
        const { ctx } = this;

        const item = await ctx.model.LostAndFound.findByPk(itemId);
        if (!item) {
            throw new Error('物品不存在');
        }

        await item.update({
            status: parseInt(status),
            updated_at: new Date()
        });

        const updatedItem = await ctx.model.LostAndFound.findByPk(itemId, {
            include: [{
                model: ctx.model.User,
                as: 'publisher',
                attributes: ['user_id', 'nickname', 'avatar', 'phone']
            }]
        });

        return updatedItem;
    }

    // 删除物品
    async deleteItem(itemId) {
        const { ctx } = this;

        const item = await ctx.model.LostAndFound.findByPk(itemId);
        if (!item) {
            throw new Error('物品不存在');
        }

        await item.destroy();
        return true;
    }
}

module.exports = LostAndFoundService;